﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using ClassLibrary.DAO;
using ClassLibrary.Data;
using System.Globalization;
using System.Drawing;


public partial class UserControl_Booking : System.Web.UI.UserControl
{
    TblPhonesDAO PhonesDAO = new TblPhonesDAO(Global.CONNECTION_STRING);
    TblFaultListDAO FaultListDAO = new TblFaultListDAO(Global.CONNECTION_STRING);
    TblJobsDAO JobsDAO = new TblJobsDAO(Global.CONNECTION_STRING);
    TblCustomersDAO customerDAO = new TblCustomersDAO(Global.CONNECTION_STRING);
    TblStatusJobDAO StatusJobDAO = new TblStatusJobDAO(Global.CONNECTION_STRING);
    TblPhoneBranDAO phoneBrandDAO = new TblPhoneBranDAO(Global.CONNECTION_STRING);
    TblModelDAO modelDAO = new TblModelDAO(Global.CONNECTION_STRING);
    TblQuoteDAO QuoteDAO = new TblQuoteDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        //btnNext.Attributes.Add("onclick", "GetvalueListBox()");
      
        if (!IsPostBack)
        {
            drJobType.Focus();
           
            drJobType.Attributes.Add("onload", "DropTypeJob_Change()");
            
            //p_wantity.Enabled = false;
            txtCusID.Enabled = false;
            //ListFault.Attributes.Add("onChange", "GetvalueListBox()");
            LoadFaultList();
            LoadBrandPhone();
            LoadModel();
           
            //txtModel.Visible = false;

            string id = Request.QueryString["id"];
          
            if (Session[Global.SESSION_LOGGED_USER] != null)
            {
                int idCus = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerIndex;
                if (id != null)
                {
                    string jobID = Request.QueryString["id"];
                    LoadJobbyID(Convert.ToInt32(jobID));
                    LoadCustomer(idCus);

                   // hyCustomer.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerFullname;
                    
                }
                else
                {
                    txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    LoadCustomer(idCus);
                   

                }
            }
            else
            {
                txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            }
        }
    }

    private void LoadModel()
    {
            //DataTable dt = modelDAO.GetModelByIdBrand(Convert.ToInt32(drBrand.SelectedValue));
            drModel.DataSource = modelDAO.GetModel();
            drModel.DataTextField = "Model";
            drModel.DataValueField = "IDModel";           
            drModel.DataBind();
            ListItem lstItem = new ListItem("- Select -", "");
            drModel.Items.Insert(0, lstItem);
            drModel.Style.Remove("top");
            drModel.Style.Remove("left");
    }

    private void LoadBrandPhone()
    {
        drBrand.DataSource = JobsDAO.LoadBrandPhone();
        
        drBrand.DataTextField = "BrandName";
        drBrand.DataValueField = "IDBrand";
        drBrand.DataBind();
        ListItem lstItem = new ListItem("-Select-", "");
        drBrand.Items.Insert(0, lstItem);
    }
    private void LoadCustomer(int JobID)
    {
        string id = Request.QueryString["id"];
        if (id == null)
        {
            if (Session[Global.SESSION_CUSTOMERS] != null)
            {
               // txtCustomer.Text = ((TblCustomers)Session[Global.SESSION_CUSTOMERS]).CustomerFullname;
                hyCustomer.Text = ((TblCustomers)Session[Global.SESSION_CUSTOMERS]).CustomerFullname;
                txtCusID.Text = ((TblCustomers)Session[Global.SESSION_CUSTOMERS]).CustomerIndex.ToString();
                hyCustomer.NavigateUrl = "~/Admin/Customer.aspx?id=" + txtCusID.Text;
            }
            else
            {
               // txtCustomer.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerFullname;
                txtCusID.Text = Global.ConvertToInt(((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerIndex.ToString()).ToString();
                hyCustomer.NavigateUrl = "~/Admin/Customer.aspx?id=" + txtCusID.Text;
                hyCustomer.Text = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerFullname;
            }           
        }
        else
        {
            DataTable dtCus = JobsDAO.GetJob((Global.ConvertToInt(id)), "");
            foreach (DataRow r in dtCus.Rows)
            {
             //   txtCustomer.Text = r["CustomerFullname"].ToString();
                txtCusID.Text = r["CustomerIndex"].ToString();
                hyCustomer.NavigateUrl = "~/Admin/Customer.aspx?id=" + txtCusID.Text;

            }
        }
        
    }

   
    private void LoadJobbyID(int JobNo)
    {
        DataTable dt_JobById = JobsDAO.GetJob(JobNo,"");


        foreach (DataRow r in dt_JobById.Rows)
        {
            txtJobNo.Text = r["JobID"].ToString();
            txtDate.Text = Convert.ToDateTime(r["DateBook"].ToString()).ToString(Global.DateFormat);
          //  txtCustomer.Text = r["CustomerFullname"].ToString();
            hyCustomer.Text = r["CustomerFullname"].ToString();
            txtCost.Text = r["AmountQuoted"].ToString();
            string CusID = r["CustomerIndex"].ToString();
            hyCustomer.NavigateUrl = "~/Admin/Customer.aspx?id=" + CusID;

            DataTable dt = StatusJobDAO.GetCurrentStatusJob(JobNo);
            foreach (DataRow dr in dt.Rows)
            {
                txtCurrentStatus.Text = dr["StatusJobs"].ToString();
                txtStatusDate.Text = Convert.ToDateTime(dr["StatusDate"]).ToString("dd/MM/yyyy");
            }

            int quot = Convert.ToInt32(r["QuotationStatus"].ToString());
            if (quot == 1)
            {
                drQuotationStatus.SelectedValue = "1";
                txtCost.Style.Value = "none";
                lblCost.Style.Value = "none";
                
                //DataTable dt = StatusJobDAO.GetCurrentStatusJob(JobNo);
                //foreach (DataRow dr in dt.Rows)
                //{
                //    txtCurrentStatus.Text = dr["StatusJobs"].ToString();
                //    txtStatusDate.Text = Convert.ToDateTime(dr["StatusDate"]).ToString("dd/MM/yyyy");
                //}
            }

            if (quot == 2)
            {
                drQuotationStatus.SelectedValue = "2";
                txtCost.Style.Value = "none";
                lblCost.Style.Value = "none";
                txtCost.Text = r["AmountQuoted"].ToString();

                //DataTable dt = StatusJobDAO.GetCurrentStatusJob(JobNo);
                //foreach (DataRow dr in dt.Rows)
                //{
                //    txtCurrentStatus.Text = dr["StatusJobs"].ToString();
                //    txtStatusDate.Text = Convert.ToDateTime(dr["StatusDate"]).ToString("dd/MM/yyyy");
                //}
            }

            if (quot == 3)
            {
                drQuotationStatus.SelectedValue = "3";
                txtCost.Style.Value = "none";
                lblCost.Style.Value = "none";
                txtCost.Text = r["AmountQuoted"].ToString();

                //DataTable dt = StatusJobDAO.GetCurrentStatusJob(JobNo);
                //foreach (DataRow dr in dt.Rows)
                //{
                //    txtCurrentStatus.Text = dr["StatusJobs"].ToString();
                //    txtStatusDate.Text = Convert.ToDateTime(dr["StatusDate"]).ToString("dd/MM/yyyy");
                //}
            }

            if (quot == 3)
            {
                drQuotationStatus.SelectedValue = "3";
                txtCost.Style.Value = "none";
                lblCost.Style.Value = "none";
                txtCost.Text = r["AmountQuoted"].ToString();
                
            }
         
            drApprovalStatus.SelectedValue = r["ApprovalStatus"].ToString();
            drJobType.SelectedValue = r["JobType"].ToString();
            if (drJobType.SelectedValue == "2")
            {
                p_wantity.Enabled = true;
                Label4.ForeColor = Color.Black;
                Label5.ForeColor = Color.Black;
                Label6.ForeColor = Color.Black;
                Label7.ForeColor = Color.Black;
                Label8.ForeColor = Color.Black;
                Label9.ForeColor = Color.Black;
                drStoreName.ForeColor = Color.Black;
                drLocation.ForeColor = Color.Black;
                drAddress.ForeColor = Color.Black;
                drProotOfPurchase.ForeColor = Color.Black;
                btnNew1.ForeColor = Color.Black;
                //drBrand.Focus();
            }
            else if (drJobType.SelectedValue == "0" || drJobType.SelectedValue == "1")
            {
                p_wantity.Enabled = false;
                Label4.ForeColor = Color.Silver;
                Label5.ForeColor = Color.Silver;
                Label6.ForeColor = Color.Silver;
                Label7.ForeColor = Color.Silver;
                Label8.ForeColor = Color.Silver;
                Label9.ForeColor = Color.Silver;
                drStoreName.ForeColor = Color.Silver;
                drLocation.ForeColor = Color.Silver;
                drAddress.ForeColor = Color.Silver;
                drProotOfPurchase.ForeColor = Color.Silver;
                btnNew1.ForeColor = Color.Silver;

            }

            txtFaultDes.Text = r["FaultDescription"].ToString();
            txtInstruction.Text = r["OrtheInstructions"].ToString();
            txtAccessories.Text = r["AccessoriesWithPhone"].ToString();

            ListItem lstItem = new ListItem(r["Model"].ToString(), "");
            drModel.Items.Insert(0, lstItem);
            //drModel.SelectedItem.Text = r["Model"].ToString();

            LoadPhoneByid(Convert.ToInt32(r["PhoneID"]));

        }
    }

    private void LoadPhoneByid(int Phoneid)
    {
        DataTable dt_PhoneByid = PhonesDAO.GetPhoneById(Phoneid);
        foreach (DataRow r in dt_PhoneByid.Rows)
        {
            txtIMEI.Text = r["IMEINo"].ToString();
            //txtModel.Text = r["Model"].ToString();
            drModel.Text = r["Model"].ToString();
            txtMSN.Text = r["PhoneMSN"].ToString();
            drBrand.SelectedValue = r["PhoneBrand"].ToString();
            drConditions.Text = r["PhoneCondition"].ToString();
            txtConditionDetails.Text = r["PhoneConditionDetails"].ToString();
            drNetwork.Text = r["PhoneNetworkWith"].ToString();
            txtLockCode.Text = r["LockPhone"].ToString();
        }
    }

    private void LoadFaultList()
    {
        ListFault.DataSource = FaultListDAO.GetFaultList();
        ListFault.DataTextField = "NameFault";
        ListFault.DataValueField = "FaultID";
        ListFault.DataBind();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session[Global.SESSION_LOGGED_USER] == null)
        {
            Response.Redirect("Login.aspx");
            return;
        }
        else
        {
            bool flag = false;
            if (txtIMEI.Text.Trim().Length == 15)
            {

                try
                {
                    #region Insert Phones

                    TblPhones phone = new TblPhones();
                    phone.IMEINo = txtIMEI.Text.Trim();
                    phone.Model = drModel.SelectedItem.Text;
                    phone.Manufacturer = drBrand.SelectedItem.Text;
                    phone.PhoneBrand = drBrand.SelectedValue;
                    phone.PhoneMSN = txtMSN.Text.Trim();
                    phone.PhoneCondition = drConditions.Text.Trim();
                    phone.PhoneConditionDetails = txtConditionDetails.Text.Trim();
                    phone.PhoneNetworkWith = drNetwork.Text.Trim();
                    phone.LockPhone = txtLockCode.Text;

                    DataTable dt = null;

                    if (txtJobNo.Text == "")
                    {
                        phone.PhoneID = 0;
                        dt = PhonesDAO.InsUpdPhone(phone, 1);
                        foreach (DataRow dr in dt.Rows)
                            phone.PhoneID = Convert.ToInt32(dr["PhoneID"].ToString());
                    }
                    else
                    {
                        int JobNo = Convert.ToInt32(txtJobNo.Text);
                        DataTable dt2 = JobsDAO.GetJob(JobNo, "");
                        foreach (DataRow dr2 in dt2.Rows)
                        {
                            phone.PhoneID = Convert.ToInt32(dr2["PhoneID"].ToString());
                        }
                        PhonesDAO.InsUpdPhone(phone, 2);
                    }
                    #endregion

                    #region Jobs
                    TblJobs Job = new TblJobs();
                    Job.CustomerIndex = Convert.ToInt32(txtCusID.Text);
                    //Job.CustomerIndex = 1;
                    Job.DateBook = DateTime.Now;
                    Job.JobType = Convert.ToInt32(drJobType.SelectedValue);

                    Job.FaultDescription = txtFaultDes.Text;
                    Job.OrtheInstructions = txtInstruction.Text;
                    Job.AccessoriesWithPhone = txtAccessories.Text;
                    Job.BookByID = Convert.ToInt32(drBookBy.SelectedValue);
                    Job.PhoneID = phone.PhoneID;
                    Job.CurrentStatus = 0;
                    Job.ExpectedCompletionDate = DateTime.Now;
                    Job.DateComplete = DateTime.Now;
                    Job.RepairCharge = 0;
                    Job.LPCharge = 0;
                    Job.OrtherCharge = 0;
                    Job.SalesAmount = Convert.ToDecimal(Convert.ToDecimal(Job.RepairCharge) + Convert.ToDecimal(Job.LPCharge) + Convert.ToDecimal(Job.OrtherCharge));

                    //if (rdCash.Checked == true)
                    //    Job.PaymentMethod = "Cash";
                    //else 
                    //    Job.PaymentMethod = "Orther";
                    Job.PaymentMethod = "";

                    Job.QuotationStatus = 1;
                    Job.ApprovalStatus = Convert.ToInt32(drApprovalStatus.SelectedValue);

                    DataTable dtJobs = null;
                    if (txtJobNo.Text == "")
                    {
                        Job.JobID = 0;

                        dtJobs = JobsDAO.InsertUpdJob(Job, 1);
                        foreach (DataRow drJob in dtJobs.Rows)
                        {
                            txtJobNo.Text = drJob["JobID"].ToString();
                        }
                        TblQuote quote = new TblQuote();
                        quote.JobID = Convert.ToInt32(txtJobNo.Text);
                        quote.InspectionFee = 0;
                        quote.AmountQuoted = 0;
                        quote.DateQuoted = DateTime.Now;
                        quote.QuoteStatus = "Book - in";
                        quote.OutCome = "";
                        quote.Notes = "";
                        quote.Itemised = "";

                        QuoteDAO.InsTblQuote(quote, 1);


                    }
                    else
                    {
                        int Jobid = Convert.ToInt32(txtJobNo.Text);
                        Job.JobID = Jobid;
                        dtJobs = JobsDAO.GetJob(Jobid, "");

                        JobsDAO.InsertUpdJob(Job, 2);
                    }

                    #endregion

                    #region StatusJob

                    TblJobStatus JobStatus = new TblJobStatus();
                    JobStatus.JobID = Convert.ToInt32(txtJobNo.Text);
                    JobStatus.StatusDate = Convert.ToDateTime(DateTime.Now);
                    JobStatus.StatusJobs = "Book - In";
                    JobStatus.Notes = JobStatus.StatusJobs;
                    StatusJobDAO.JobStatusIns(JobStatus);

                    #endregion                

                    flag = true;
                }
                catch (Exception ex)
                {
                    Session[Global.SESSION_ERROR] = ex;
                    Response.Redirect(Global.ERROR_PAGE);
                }
                if (flag)
                {
                    message_green.Style.Value = "inline";
                    System.Threading.Thread.Sleep(3000);
                    Response.Redirect("~/Admin/Booking.aspx?id=" + txtJobNo.Text);
                }
            }
            else
            {
               /// btnSave.Attributes.Add("onClick", "alert(' Phone IMEI No must be enough 15 characters');");
               // txtIMEI.Focus();

                ScriptManager.RegisterStartupScript(btnSave, btnSave.GetType(), "alert", "alert(' Phone IMEI No must be enough 15 characters');", true);
                txtIMEI.Focus();
            }
        }
       
      }

    protected void btnPrint_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/Reports.aspx?id=" + txtJobNo.Text);
    } 

    protected void btnNext_Click(object sender, EventArgs e)
    {
        txtFaultDes.Text += ListFault.SelectedItem.Text + "; ";
        
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/Booking.aspx");
    }
    protected void btnHome_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Admin/Default.aspx");
    }
    //protected void drJobType_SelectedIndexChanged(object sender, EventArgs e)
    //{
      
    //}
    protected void drBrand_SelectedIndexChanged(object sender, EventArgs e)
    {
 
        DataTable dt = modelDAO.GetModelByIdBrand(Convert.ToInt32(drBrand.SelectedValue));
        foreach (DataRow dr in dt.Rows)
        {
            drModel.DataSource = dt;
            drModel.DataTextField = "Model";
            drModel.DataValueField = "Model";    
            drModel.DataBind();
        }

    }

    protected void drJobType_SelectedIndexChanged1(object sender, EventArgs e)
    {
        if (drJobType.SelectedIndex == 2)
        {
            p_wantity.Enabled = true;
            Label4.ForeColor = Color.Black;
            Label5.ForeColor = Color.Black;
            Label6.ForeColor = Color.Black;
            Label7.ForeColor = Color.Black;
            Label8.ForeColor = Color.Black;
            Label9.ForeColor = Color.Black;
            drStoreName.ForeColor = Color.Black;
            drLocation.ForeColor = Color.Black;
            drAddress.ForeColor = Color.Black;
            drProotOfPurchase.ForeColor = Color.Black;
            btnNew1.ForeColor = Color.Black;
            //drBrand.Focus();
           
        }
        else
        {
            p_wantity.Enabled = false;
            Label4.ForeColor = Color.Silver;
            Label5.ForeColor = Color.Silver;
            Label6.ForeColor = Color.Silver;
            Label7.ForeColor = Color.Silver;
            Label8.ForeColor = Color.Silver;
            Label9.ForeColor = Color.Silver;
            drStoreName.ForeColor = Color.Silver;
            drLocation.ForeColor = Color.Silver;
            drAddress.ForeColor = Color.Silver;
            drProotOfPurchase.ForeColor = Color.Silver;
            btnNew1.ForeColor = Color.Silver;
            drBrand.Focus();
        }
    }
}
